import api from "./request.js"
import config from "./config";
import utils from "./utils";

const accountInfo = wx.getAccountInfoSync();
const app_id = accountInfo.miniProgram.appId
let num = 1
let interceptor = {
	/* 请求拦截 */
	requestHttp(reqHttp, reject) {
		reqHttp.requestId = new Date().getTime()
		return true
	},
	/* 响应拦截处理 */
	success(response, resolve, reject) {
		if (response.data.code == 401 && num == 1) {
			num = 0
			uni.removeStorageSync('token');
			uni.removeStorageSync('user', null);
			if (uni.getStorageSync('openid')) {
				login()
			} else {
				let pages = getCurrentPages(); // 获取栈实例
				const perpage = pages[pages.length - 1]
				let url = '/' + perpage.route + '?'
				for (let i in perpage.options) {
					console.log(i, perpage.options[i])
					url = url + i + '=' + perpage.options[i] + '&'
				}
				uni.setStorageSync('pageUrl', url);
				uni.reLaunch({
					url: '/login/index'
				})
				setTimeout(() => {
					num = 1
				}, 2000)
			}
		}
		if (response.data.code == 403) {
			uni.$u.toast('无权限操作')
			setTimeout(() => {
				utils.back();
			}, 1000)
		}
		if (response.statusCode == 200) {
			if (response.data.code == 0) {
				resolve(response.data);
			} else {
				reject(response.data);
			}
		} else {
			reject(response);
		}
	},
	/* 网络请求错误 */
	fail(err, resolve, reject) {
		reject(err)
	}
}

function login() {
	uni.$u.toast('登录过期,重新登录')
	uni.showLoading({
		title: '登录中...',
	})
	uni.login({
		provider: 'weixin', //使用微信登录
		success: (loginRes) => {
			const loginCode = loginRes.code
			getOpenidAndSession(loginCode)
		},
		fail: () => {
			uni.hideLoading()
			num = 1
		}
	});
}

function getOpenidAndSession(loginCode) {
	api.Login.Session({
		code: loginCode
	}).then(res => {
		loginSilent()
	}).catch(err => {
		uni.hideLoading()
		num = 1
	})
}

function loginSilent() {
	wx.getUserInfo({
		success: resUser => {
			api.Login.Silent({
				openId: uni.getStorageSync('openid'),
				rawData: resUser.rawData,
				signature: resUser.signature,
				encryptedData: resUser.encryptedData,
				iv: resUser.iv
			}).then(res => {
				uni.setStorageSync('token', res.data.token);
				uni.setStorageSync('user', res.data.user);
				let pages = getCurrentPages(); // 获取栈实例
				const perpage = pages[pages.length - 1]
				let url = '/' + perpage.route + '?'
				for (let i in perpage.options) {
					console.log(i, perpage.options[i])
					url = url + i + '=' + perpage.options[i] + '&'
				}
				uni.reLaunch({
					url: url
				})
				uni.hideLoading()
				num = 1
			}).catch(err => {
				uni.hideLoading()
				num = 1
			})
		}
	})
}
export function request(url, option) {
	/* Object: objQr */
	// function objToQuery(objQr) {
	// 	if (!objQr) return ''
	// 	let strData = ''
	// 	try {
	// 		for (var key in objQr) {
	// 			strData += `${key}=${objQr[key]}&`
	// 		}
	// 		if (strData) {
	// 			strData = '?' + strData.slice(0, -1)
	// 		}
	// 	} catch (e) {
	// 		strData = ''
	// 	}
	// 	return strData
	// }
	const httpOption = {
		url: config.url + url,
		header: Object.assign({
			/* 默认请求头 */
			'Content-Type': 'application/json;charset=UTF-8',
			'Authorization': "Bearer " + uni.getStorageSync('token')
		}, option.header),
		data: option.data || {},
		method: option.method,
		/* 如设为json，会对返回的数据做一次 JSON.parse */
		dataType: "json",
		responseType: "text",
	};
	return new Promise((resolve, reject) => {
		httpOption.success = (res) => interceptor.success(res, resolve, reject)
		httpOption.fail = (err) => interceptor.success(err, resolve, reject)
		httpOption.complete = (answer) => {}
		httpOption.option = option
		/* 同意请求处理*/
		if (interceptor.requestHttp(httpOption, reject)) {
			uni.request(httpOption);
		}

	})
}
export function get(url, data, options = {}) {
	options.url = url
	options.data = {
		...data,
		app_id: app_id,
	}
	options.method = 'GET'
	return request(url, options)
}
export function post(url, data, options = {}) {
	options.url = url
	options.data = {
		...data,
		app_id: app_id,
	}
	options.method = 'POST'
	return request(url, options)
}

export function put(url, data, options = {}) {
	options.url = url

	options.data = {
		...data,
		app_id: app_id,
	}
	options.method = 'PUT'
	return request(url, options)
}
export function del(url, data, options = {}) {
	options.url = url

	options.data = {
		...data,
		app_id: app_id,
	}
	options.method = 'DELETE'
	return request(url, options)
}